package loader

import (
	"bytes"
	"fmt"

	"github.com/hashicorp/consul/api"
	"github.com/spf13/viper"
)

func LoadConfigFromConsul(key string) error {
	config := api.DefaultConfig()
	client, err := api.NewClient(config)
	if err != nil {
		return fmt.Errorf("failed to create Consul client: %w", err)
	}

	kv := client.KV()
	pair, _, err := kv.Get(key, nil)
	if err != nil {
		return fmt.Errorf("failed to get config from Consul: %w", err)
	}

	if pair == nil {
		return fmt.Errorf("config key not found in Consul")
	}

	viper.SetConfigType("yaml")
	if err := viper.ReadConfig(bytes.NewBuffer(pair.Value)); err != nil {
		return fmt.Errorf("failed to read config from Consul: %w", err)
	}

	return nil
}
